<template>
  <div 
    class="yh_list" 
    ref="liWrap" 
    :style="{height:height}" 
    @scroll="scrollEvent($event)"
  >
    <div class="yh_cont" ref="yh_cont" :style="{height:listArr.length*itemHeight+'px'}"></div>
    <div class="yh_scroll" :style="{translate:'0px '+(translateY)+'px'}">
      <div 
        class="yh_lis"
        v-for="(val,idx) in listData" 
        :key="idx"
      >
        <slot name="cont" :listCont="val" :listIdx="idx"></slot>
      </div>
    </div>
  </div>
</template>
<script>
// 200显示不出
// 向上，不流畅
export default {
  name: 'yh_virtual_list',
  data(){
    return {
      startIdx:0,
      endIdx:10,
      count:1,//可以同时显示出多少条
      translateY:0,
    }
  },
  props:{
    listArr:{
      type:Array,
      default:()=>[]
    },
    itemHeight:{
      type:Number,
      default:40,
    },
    height:{
      type:Number | String,
      default:'100%'
    },
    preCount:{
      type:Number,
      default:10,
    },
    belowCount:{
      type:Number,
      default:10,
    },
    scrollDown:{
      type:Event,
      default:()=>{}
    },
    scrollTop:{
      type:Event,
      default:()=>{}
    }
  },
  watch:{
    listArr:{
      handler(){
        this.getEndIdx();
      },
      immediate:true,
    }
  },
  mounted(){
    this.$nextTick(()=>{
      this.getCount();
      this.getStartIdx(0);
      this.getEndIdx();
      this.initContHeight();
    })
  },
  computed:{
    listData(){
      return this.listArr.slice(this.startIdx,this.endIdx);
    }
  },
  methods: {
    initContHeight(){
      this.$refs.yh_cont.height = this.listArr.length * this.itemHeight + "px";
    },
    scrollEvent(event){
      let scrollTop = event.target.scrollTop;  

      if(scrollTop >= (this.listArr.length - this.count) * this.itemHeight){
        this.$emit('scrollDown');
      }else{
        this.translateY = scrollTop;
        let index = Math.floor(scrollTop/this.itemHeight);
      
        this.getStartIdx(index);
        this.getEndIdx();

        if(scrollTop<=0){
          this.$emit('scrollTop');
        }
      }
    },
    getCount(){
      var count = Math.ceil(this.$refs.liWrap.offsetHeight/this.itemHeight);

      this.count = Math.max(1,count);
    },
    getStartIdx(startIdx){
      this.startIdx = Math.max(startIdx,0);
    },
    getEndIdx(){
      var endIdx = this.startIdx + this.count + this.belowCount;

      this.endIdx = Math.min(endIdx,this.listArr.length);
    }
  },
};
</script>
<style scoped>
.yh_list{
  position:relative;
  overflow: auto;
  height: 100%;
}
.yh_cont{
  position:absolute;
  z-index:-1;
  top:0;
  left:0;
  right:0;
}
.yh_lis{
  height:40px;
  line-height:40px;
}
</style>
